<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Cirpho extends Public_Controller
{
	public $limit = 5; // TODO: PS - Make me a settings option

	public function __construct()
	{
		parent::Public_Controller();
		$this->load->model('cip_categories_m');
		$this->load->model('cip_samples_m');
		$this->load->model('cip_settings_m');
		$this->load->model('cip_texts_m');
		$this->load->helper(array('url'));
		
		$this->config->load('cirpho');
		$this->load->helper('text');
		$this->_uploadPath = FCPATH . $this->config->item('upload_folder');
		$this->_command_folder = $this->config->item('command_folder');
		$this->_path = FCPATH . $this->config->item('files_folder');
		$this->_thumFolderPath = $this->config->item('files_thums_folder');
	}
	public function index(){
		/*
		$out = shell_exec("/usr/bin/match -im1 ".$this->_path."home-2.jpg.pgm -k1 ".$this->_path."home-2.jpg.key -im2 ".$this->_path."home-2_1.jpg.pgm -k2 ".$this->_path."home-2_1.jpg.key >/dev/null 2> /tmp/cirpho123");
		
		//print $out ? $out : join("", file("/tmp/cirpho123"));
		$match = $out ? $out : join("", file("/tmp/cirpho123"));
		echo $match;
		die();
		
		*/
		if ($_REQUEST['image']) {
			// convert the image data from base64
			$imgData = base64_decode($_REQUEST['image']);
			
			// set the image paths
			$fileName = md5(date('Ymdgisu')) . '.jpg';
			//$file = $this->_uploadPath . md5(date('Ymdgisu')) . '.jpg';
			$file = $this->_uploadPath . $fileName;
			//$url = 'http://www.mysite.com' . $file; 
			
			// delete the image if it already exists
			if (file_exists($file)) { unlink($file); }
			
			// write the imgData to the file
			$fp = fopen($file, 'w');
			fwrite($fp, $imgData);
			fclose($fp);
			$categoryId = $_POST['categoryId'];
			if($categoryId == "0"){
				$samples = $this->cip_samples_m->getSamples();
			}else{
				$samples = $this->cip_samples_m->getSamplesByCategory($categoryId);
			}
			$max_width = $this->cip_settings_m->get('max_width');
			$minimum_matching_rate = $this->cip_settings_m->get('minimum_matching_rate');
			$decision_matching_rate = $this->cip_settings_m->get('decision_matching_rate');
			
			system("/usr/bin/convert ".$this->_uploadPath.$fileName." -resize ".$max_width->value." -type Grayscale -depth 8 ".$this->_uploadPath.$fileName.".pgm");
			//system($this->_command_folder.'sift < '.$this->_uploadPath.$fileName.'.pgm >'.$this->_uploadPath.$fileName.'.key 2>/tmp/fasjegjegioag123.tmp');
			$siftOut = shell_exec($this->_command_folder.'sift < '.$this->_uploadPath.$fileName.'.pgm >'.$this->_uploadPath.$fileName.'.key 2>/tmp/siftcirpho123');
			$keyPoint = $siftOut ? $siftOut : join("", file("/tmp/siftcirpho123"));
			//echo $keyPoint;
			//Finding keypoints... 83 keypoints found.
			$keyPoint = str_replace("Finding keypoints...","",$keyPoint);
			$keyPoint = trim(str_replace("keypoints found.","",$keyPoint));
			
			$matches = array();
			foreach ($samples as $sample){
				$out = shell_exec($this->_command_folder."match -im1 ".$this->_path.$sample->image.".pgm -k1 ".$this->_path.$sample->image.".key -im2 ".$this->_uploadPath.$fileName.".pgm -k2 ".$this->_uploadPath.$fileName.".key >/dev/null 2> /tmp/cirpho123");
				$match = $out ? $out : join("", file("/tmp/cirpho123"));
				if(!strpos($match, "Error")){
					$match = str_replace("Found","",$match);
					$match = trim(str_replace("matches.","",$match));
					//echo round(($match/$keyPoint)*100, 0)."<br/>";
					if($minimum_matching_rate->value <= round($match/$keyPoint*100, 0)){
						$matches[] = array(
									'decision_matching_rate' => $decision_matching_rate->value,
									'keypoint' => $keyPoint,
									'match'	 => $match,
									'matchPercent' => round($match/$keyPoint*100, 0),
									'image' => base_url() . $this->_thumFolderPath .$sample->image,
									'url' => $sample->url,
									'title' => $sample->title,
									'comment' => $sample->comment
									);
					}
					if($decision_matching_rate->value <= round($match/$keyPoint*100, 0)){
						break;
					}
				}
			}
			echo json_encode($matches);
		}
	}
	public function category(){
		$categories = $this->cip_categories_m->order_by('name')->get_all();
		echo json_encode($categories);
	}
	public function howtouse(){
		$howToUse = $this->cip_texts_m->get('how_to_use');
		echo json_encode($howToUse);
	}
	public function report(){
		if ($_REQUEST['result']) {
			echo $_REQUEST['result'];
		}
	}
}
?>